//
//  FACEViewController.m
//  WZEfengAndEtong
//
//  Created by 李旭 on 16/8/10.
//  Copyright © 2016年 wanzhao. All rights reserved.
//

#import "FACEViewController.h"
#import "Masonry.h"
#import "FaceppPerson.h"
#import "FaceppGroup.h"
#import "FaceppClient.h"
#import "FaceppTrainer.h"
#import "FaceppResult.h"
#import "FaceppDetection.h"
#import "CContactMgr.h"
#import "CContactModel.h"

#import "MBProgressHUD+WZ.h"
@interface FACEViewController ()<UIImagePickerControllerDelegate,UINavigationControllerDelegate>
@property(nonatomic,copy) NSString *companyName;
@property(nonatomic,strong) UIImageView *screenshot;
@property(nonatomic,strong) UILabel *numberLabel;
@property(nonatomic,strong) UIButton *getButton;
@property(nonatomic,strong) UIButton *upButton;
@property(nonatomic,strong) CContactModel *currentUser;
@property(nonatomic,copy) NSString *faceId;
@property(nonatomic,assign) NSInteger faceCount;
@end

@implementation FACEViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
    [self.navigationItem setNewTitleCenter:@"人脸录制"];
    [self configUser];
    [self configInterFace];
}
-(void)configUser
{
    self.currentUser = [[[CContactMgr alloc]init] loadCurContact];
    NSRange range = [_currentUser.Email rangeOfString:@"@"];
    self.companyName = [_currentUser.Email substringFromIndex:range.location+1];
    NSRange range1 = [self.companyName rangeOfString:@"."];
    self.companyName = [self.companyName substringToIndex:range1.location];
}
-(void)checkGroup
{
    
    FaceppResult *result = [[[FaceppGroup alloc]init] getInfoWithGroupName:self.companyName orGroupId:nil];
    if (!result.success) {
        if (result.content == nil) {
            [MBProgressHUD showError:@"网络错误 请稍后再试"];
            UIView *view = [[UIView alloc]init];
            view.backgroundColor = [UIColor clearColor];
            [self.view addSubview:view];
            [view mas_makeConstraints:^(MASConstraintMaker *make) {
                make.right.left.top.bottom.mas_equalTo(0);
            }];
        }
        else
        {
      FaceppResult *result = [[[FaceppGroup alloc]init] createWithGroupName:self.companyName];
            if (result.success) {
                [self checkPerson];

            }
        }
      }
    else
    {
        [self checkPerson];
    }
    
}
-(void)checkPerson
{
    
    FaceppResult *result  = [[[FaceppPerson alloc]init] getInfoWithPersonName:self.currentUser.UserName orPersonId:nil];
    if (!result.success) {
            [[[FaceppPerson alloc]init] createWithPersonName:self.currentUser.UserName andFaceId:nil andTag:nil andGroupId:nil orGroupName:@[self.companyName]];
    }
    else
    {
        self.faceCount = [result.content[@"face"] count];
        self.numberLabel.text = [NSString stringWithFormat:@"已录制%ld个人脸",(long)self.faceCount];
        if (self.faceCount>2) {
            [self.upButton removeFromSuperview];
            [self.getButton removeFromSuperview];
        }
        if (self.faceCount>0) {
            [USER_DEFAULT setBool:YES forKey:@"haveFace"];
            [USER_DEFAULT synchronize];
        }
    }
}
-(void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    [self checkGroup];
    
}
-(void)configInterFace
{
    __weak typeof (self) weakself = self;
    self.numberLabel = [[UILabel alloc]init];
    _numberLabel.textAlignment = NSTextAlignmentCenter;
    _numberLabel.text = @"loading...";
    [self.view addSubview:_numberLabel];
    [_numberLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(20);
        make.width.mas_equalTo(200);
        make.height.mas_equalTo(40);
        make.centerX.mas_equalTo(weakself.view);
    }];
    self.screenshot = [[UIImageView alloc]init];
    self.screenshot.image = [UIImage imageNamed:@"faceman"];
    [self.view addSubview:_screenshot];
    [_screenshot mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(weakself.numberLabel.mas_bottom).offset(20);
        make.left.mas_offset(50);
        make.right.mas_offset(-50);
        make.height.mas_offset(self.view.width - 100);
    }];
    self.getButton = [[UIButton alloc]init];
    [self.getButton addTarget:self action:@selector(getImage) forControlEvents:UIControlEventTouchUpInside];
    self.getButton.backgroundColor = [UIColor blueColor];
    [self.getButton setTitle:@"开始获取" forState:UIControlStateNormal];
    self.getButton.layer.cornerRadius = 5;
    self.getButton.layer.masksToBounds = YES;
    [self.view addSubview:_getButton];
    [_getButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.width.mas_equalTo(100);
        make.height.mas_equalTo(30);
        make.top.equalTo(weakself.screenshot.mas_bottom).offset(20);
        make.centerX.mas_equalTo(weakself.view);
    }];
    self.upButton = [[UIButton alloc]init];
    [self.upButton addTarget:self action:@selector(upImage) forControlEvents:UIControlEventTouchUpInside];
    self.upButton.backgroundColor = [UIColor greenColor];
    self.upButton.enabled = NO;
    [self.upButton setTitle:@"确定上传" forState:UIControlStateNormal];
    self.upButton.layer.cornerRadius = 5;
    self.upButton.layer.masksToBounds = YES;
    [self.view addSubview:_upButton];
    [_upButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.width.mas_equalTo(100);
        make.height.mas_equalTo(30);
        make.top.equalTo(weakself.getButton.mas_bottom).offset(20);
        make.centerX.mas_equalTo(weakself.view);
    }];
   
}
-(void)getImage
{
    if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
        UIImagePickerController *picker = [[UIImagePickerController alloc]init];
        picker.sourceType = UIImagePickerControllerSourceTypeCamera;
        picker.delegate = self;
        picker.cameraDevice = UIImagePickerControllerCameraDeviceFront;
        [self presentViewController:picker animated:YES completion:nil];
    }
    else
    {
        [MBProgressHUD showError:@"请检查您的摄像头"];
    }

}
#pragma mark -- imagePakerDeleagate
-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info
{
    UIImage *image = [info objectForKey:UIImagePickerControllerOriginalImage];
    _screenshot.image = image;
    [picker dismissViewControllerAnimated:YES completion:nil];
    self.upButton.enabled = YES;
    
}
-(void)upImage
{
    MBProgressHUD* progress = [[MBProgressHUD alloc] initWithView:self.view];
    [progress setAlpha:0.5];
    progress.removeFromSuperViewOnHide = YES;
    [progress setLabelText:@"正在上传..."];
    [self.view addSubview:progress];
    [self.view bringSubviewToFront:progress];
    [progress show:YES];

    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        UIImage *image = [self fixOrientation:_screenshot.image];
        NSData *data = UIImageJPEGRepresentation(image, 1.0);
        FaceppResult *result =  [[[FaceppDetection alloc]init] detectWithURL:nil orImageData:data mode:FaceppDetectionModeOneFace];
        if (result.success) {
            NSArray *faceArray = result.content[@"face"] ;
            if (faceArray.count>0) {
                self.faceId = faceArray.firstObject[@"face_id"];
                FaceppResult *result = [[[FaceppPerson alloc]init] addFaceWithPersonName:self.currentUser.UserName orPersonId:nil andFaceId:@[self.faceId]];
                if (result.success) {
                    self.faceCount++;
                    dispatch_async(dispatch_get_main_queue(), ^{
                        self.numberLabel.text = [NSString stringWithFormat:@"您已有%ld个人脸",(long)self.faceCount];
                        [MBProgressHUD showSuccess:@"上传成功"];
                        [MBProgressHUD hideHUDForView:self.view];
                        [USER_DEFAULT setBool:YES forKey:@"haveFace"];
                        [USER_DEFAULT synchronize];
                        if (self.faceCount>2) {
                            [self.upButton removeFromSuperview];
                            [self.getButton removeFromSuperview];
                        }
                        self.screenshot.image = [UIImage imageNamed:@"faceman"];
                        self.upButton.enabled = NO;

                    });
                    
                    [self trainPerson];
                    [self trainGroup];
                }
            }
            else
            { dispatch_async(dispatch_get_main_queue(), ^{
                [MBProgressHUD showError:@"添加人脸失败"];
                   });
            }
        }
        else
        {
            dispatch_async(dispatch_get_main_queue(), ^{
            [MBProgressHUD showError:@"人脸认证失败 请重新录制"];
             });
        }

    });
}
- (UIImage *)fixOrientation:(UIImage *)aImage {
    
    // No-op if the orientation is already correct
    if (aImage.imageOrientation == UIImageOrientationUp)
        return aImage;
    
    // We need to calculate the proper transformation to make the image upright.
    // We do it in 2 steps: Rotate if Left/Right/Down, and then flip if Mirrored.
    CGAffineTransform transform = CGAffineTransformIdentity;
    
    switch (aImage.imageOrientation) {
        case UIImageOrientationDown:
        case UIImageOrientationDownMirrored:
            transform = CGAffineTransformTranslate(transform, aImage.size.width, aImage.size.height);
            transform = CGAffineTransformRotate(transform, M_PI);
            break;
            
        case UIImageOrientationLeft:
        case UIImageOrientationLeftMirrored:
            transform = CGAffineTransformTranslate(transform, aImage.size.width, 0);
            transform = CGAffineTransformRotate(transform, M_PI_2);
            break;
            
        case UIImageOrientationRight:
        case UIImageOrientationRightMirrored:
            transform = CGAffineTransformTranslate(transform, 0, aImage.size.height);
            transform = CGAffineTransformRotate(transform, -M_PI_2);
            break;
        default:
            break;
    }
    
    switch (aImage.imageOrientation) {
        case UIImageOrientationUpMirrored:
        case UIImageOrientationDownMirrored:
            transform = CGAffineTransformTranslate(transform, aImage.size.width, 0);
            transform = CGAffineTransformScale(transform, -1, 1);
            break;
            
        case UIImageOrientationLeftMirrored:
        case UIImageOrientationRightMirrored:
            transform = CGAffineTransformTranslate(transform, aImage.size.height, 0);
            transform = CGAffineTransformScale(transform, -1, 1);
            break;
        default:
            break;
    }
    
    // Now we draw the underlying CGImage into a new context, applying the transform
    // calculated above.
    CGContextRef ctx = CGBitmapContextCreate(NULL, aImage.size.width, aImage.size.height,
                                             CGImageGetBitsPerComponent(aImage.CGImage), 0,
                                             CGImageGetColorSpace(aImage.CGImage),
                                             CGImageGetBitmapInfo(aImage.CGImage));
    CGContextConcatCTM(ctx, transform);
    switch (aImage.imageOrientation) {
        case UIImageOrientationLeft:
        case UIImageOrientationLeftMirrored:
        case UIImageOrientationRight:
        case UIImageOrientationRightMirrored:
            // Grr...
            CGContextDrawImage(ctx, CGRectMake(0,0,aImage.size.height,aImage.size.width), aImage.CGImage);
            break;
            
        default:
            CGContextDrawImage(ctx, CGRectMake(0,0,aImage.size.width,aImage.size.height), aImage.CGImage);
            break;
    }
    CGImageRef cgimg = CGBitmapContextCreateImage(ctx);
    UIImage *img = [UIImage imageWithCGImage:cgimg];
    CGContextRelease(ctx);
    CGImageRelease(cgimg);
    return img;
}
-(void)trainGroup
{
    [[[FaceppTrainer alloc]init] trainAsynchronouslyWithId:nil orName:self.companyName andType:FaceppTrainIdentify];
}
-(void)trainPerson
{
        [[[FaceppTrainer alloc]init] trainAsynchronouslyWithId:nil orName:self.currentUser.UserName     andType:FaceppTrainVerify];
}

@end
